package com.warehouse.dao.impl;

import com.warehouse.dao.UserDao;
import com.warehouse.dao.common.HibernateUtil;
import com.warehouse.entity.Admin;
import com.warehouse.entity.Cargotype;
import com.warehouse.entity.User;
import org.hibernate.Query;

import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public int add(User user) {
        try {
            HibernateUtil.currentSession().save(user);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int update(User user) {
        try {
            HibernateUtil.currentSession().update(user);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int delete(int id) {
        try {
            //先获取id
            User user = (User) HibernateUtil.currentSession().get(User.class,id);
            HibernateUtil.currentSession().delete(user);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public List<User> allPage(int startPage, int pageSize) {
        Query query = HibernateUtil.currentSession().createQuery("from User");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    @Override
    public int count() {
        return HibernateUtil.currentSession().createQuery("from User").list().size();
    }

    @Override
    public User byId(int id) {
        User user = (User) HibernateUtil.currentSession().get(User.class,id);
        return user;
    }

    @Override
    public List<User> byAdminNum(int startPage, int pageSize, String name) {
        Query query = HibernateUtil.currentSession().createQuery("from User a where a.name like '%" + name + "%'");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    @Override
    public int countByAdminNum(String name) {
        return HibernateUtil.currentSession().createQuery("from User a where a.name like '%" + name + "%'").list().size();
    }
}
